package com.csd.controller;

import com.csd.dto.ActionResult;
import com.csd.dto.JsonBean;
import com.csd.po.SysUser;
import com.csd.service.UserService;
import com.csd.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * 用户注册登录模块
 *
 * @program: CeSuDi_SSM
 * @author: qinjianbao
 * @create: 2020-12-22 16:04
 * @Version: 1.0
 */
@Controller
public class UserController {

    //注入service层
    @Autowired(required = false)
    private UserService userService;

    /**
     * 登录模块
     *
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public JsonBean login(String tel, String password, HttpSession session) {

        System.out.println(tel);
        SysUser login = userService.findByNameAndPwd(tel, password);
        System.out.println(login);
        if (login != null) {
            session.setAttribute("user", login);
            //十五分钟后失效
            session.setMaxInactiveInterval(900);
            JsonBean jsonBean = new JsonBean(200, 1, null, login);
            return jsonBean;

        }
        return null;
    }

    @RequestMapping("/logout")
    @ResponseBody
    public JsonBean logout(HttpSession session) {
        session.removeAttribute("user");
        return JsonUtils.createJsonBean(200,"退出登录成功");
    }

    /**
     * 跳转到成功页面
     *
     * @return
     */
    @RequestMapping(value = "/loginsuccess", method = RequestMethod.GET)
    public String loginsuccess() {

        return "pagehome/loginsuccess";
    }
    /**
     * 用户注册模块
     */
    @RequestMapping(value = "/register" ,method = RequestMethod.POST)
    @ResponseBody
    public JsonBean register(SysUser sysUser){
        JsonBean bean=null;
        SysUser sysUserTel = userService.findByTel(sysUser.getTel());
        if(sysUserTel == null){
            userService.insertUser(sysUser);
            bean= JsonUtils.createJsonBean(200,sysUser);

        }
        else {
            bean=JsonUtils.createJsonBean(400,sysUser);
        }

        return bean;
    }

    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    @ResponseBody
    public JsonBean updateUser(SysUser sysUser){
        JsonBean res;
        userService.updateUser(sysUser);
        res = JsonUtils.createJsonBean(200, "修改成功");
        return res;
    }
}
